#!/bin/sh

### BEGIN INIT INFO
# Provides:          eturnal
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop eturnal
# Description:       Control the STUN/TURN service provided by eturnal.
### END INIT INFO

name='eturnal'
eturnalctl='{{eturnal_prefix}}/bin/eturnalctl'
PATH='/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin'
export PATH

if [ $# -ne 1 ]
then
    echo >&2 "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status}"
    exit 2
fi
if ! [ -x "$eturnalctl" ]
then
    if type 'eturnalctl' >'/dev/null'
    then
        eturnalctl='eturnalctl'
    else
        echo >&2 "Cannot execute $eturnalctl"
        exit 5
    fi
fi

case $1 in
start)
    if "$eturnalctl" 'status' >'/dev/null'
    then
        echo "$name is already running."
    else
        printf "Starting $name ... "
        if "$eturnalctl" 'daemon' >'/dev/null'
        then
            echo 'done.'
        else
            echo 'FAILED.'
            exit 1
        fi
    fi
    ;;
stop)
    if ! "$eturnalctl" 'status' >'/dev/null'
    then
        echo "$name is already stopped."
    else
        printf "Stopping $name ... "
        if "$eturnalctl" 'stop' >'/dev/null'
        then
            echo 'done.'
        else
            echo 'FAILED.'
            exit 1
        fi
    fi
    ;;
restart)
    if "$eturnalctl" 'status' >'/dev/null'
    then
        printf "Restarting $name ... "
        if "$eturnalctl" 'restart' >'/dev/null'
        then
            echo 'done.'
        else
            echo 'FAILED.'
            exit 1
        fi
    else
        exec "$0" 'start'
    fi
    ;;
try-restart)
    if "$eturnalctl" 'status' >'/dev/null'
    then
        printf "Restarting $name ... "
        if "$eturnalctl" 'restart' >'/dev/null'
        then
            echo 'done.'
        else
            echo 'FAILED.'
            exit 1
        fi
    else
        echo "$name is NOT running."
    fi
    ;;
reload|force-reload)
    if "$eturnalctl" 'status' >'/dev/null'
    then
        printf "Reloading $name ... "
        if "$eturnalctl" 'reload' >'/dev/null'
        then
            echo 'done.'
        else
            echo 'FAILED.'
            exit 1
        fi
    else
        echo "$name is NOT running."
        exit 7
    fi
    ;;
status)
    if "$eturnalctl" 'status' >'/dev/null'
    then
        echo "$name is running."
    else
        echo "$name is NOT running."
        exit 3
    fi
    ;;
*)
    echo >&2 "Usage: $0 {start|stop|restart|try-restart|reload|force-reload|status}"
    exit 2
    ;;
esac
exit 0
